from flask import Blueprint, request, jsonify
from app import db
from app.models.datasource import DataSource
from app.services.datasource_service import test_connection, get_tables, get_table_schema
import json
from datetime import datetime

datasource_bp = Blueprint('datasource', __name__)

@datasource_bp.route('/', methods=['GET'])
def get_datasources():
    """获取所有数据源"""
    datasources = DataSource.query.all()
    return jsonify({
        'code': 200,
        'data': [ds.to_dict() for ds in datasources]
    })

@datasource_bp.route('/<int:id>', methods=['GET'])
def get_datasource(id):
    """获取单个数据源"""
    datasource = DataSource.query.get_or_404(id)
    return jsonify({
        'code': 200,
        'data': datasource.to_dict()
    })

@datasource_bp.route('/', methods=['POST'])
def create_datasource():
    """创建数据源"""
    data = request.json
    
    # 检查必填字段
    required_fields = ['name', 'host', 'port', 'username', 'password', 'database']
    for field in required_fields:
        if field not in data:
            return jsonify({
                'code': 400,
                'message': f'缺少必填字段: {field}'
            })
    
    # 检查名称是否已存在
    if DataSource.query.filter_by(name=data['name']).first():
        return jsonify({
            'code': 400,
            'message': '数据源名称已存在'
        })
    
    # 创建数据源
    datasource = DataSource(
        name=data['name'],
        type=data.get('type', 'mysql'),
        host=data['host'],
        port=data['port'],
        username=data['username'],
        password=data['password'],
        database=data['database'],
        description=data.get('description', ''),
        status='unknown'  # 初始状态为未知
    )
    
    db.session.add(datasource)
    db.session.commit()
    
    return jsonify({
        'code': 200,
        'message': '数据源创建成功',
        'data': datasource.to_dict()
    })

@datasource_bp.route('/<int:id>', methods=['PUT'])
def update_datasource(id):
    """更新数据源"""
    datasource = DataSource.query.get_or_404(id)
    data = request.json
    
    # 更新字段
    if 'name' in data and data['name'] != datasource.name:
        # 检查名称是否已存在
        if DataSource.query.filter_by(name=data['name']).first():
            return jsonify({
                'code': 400,
                'message': '数据源名称已存在'
            })
        datasource.name = data['name']
    
    if 'type' in data:
        datasource.type = data['type']
    if 'host' in data:
        datasource.host = data['host']
    if 'port' in data:
        datasource.port = data['port']
    if 'username' in data:
        datasource.username = data['username']
    if 'password' in data:
        datasource.password = data['password']
    if 'database' in data:
        datasource.database = data['database']
    if 'description' in data:
        datasource.description = data['description']
    
    db.session.commit()
    
    return jsonify({
        'code': 200,
        'message': '数据源更新成功',
        'data': datasource.to_dict()
    })

@datasource_bp.route('/<int:id>', methods=['DELETE'])
def delete_datasource(id):
    """删除数据源"""
    datasource = DataSource.query.get_or_404(id)
    
    # 检查是否有关联的同步任务
    if datasource.source_tasks.count() > 0 or datasource.target_tasks.count() > 0:
        return jsonify({
            'code': 400,
            'message': '该数据源有关联的同步任务，无法删除'
        })
    
    db.session.delete(datasource)
    db.session.commit()
    
    return jsonify({
        'code': 200,
        'message': '数据源删除成功'
    })

@datasource_bp.route('/test_connection', methods=['POST'])
def test_datasource_connection():
    """测试数据源连接"""
    data = request.json
    
    # 检查必填字段
    required_fields = ['host', 'port', 'username', 'password', 'database']
    for field in required_fields:
        if field not in data:
            return jsonify({
                'code': 400,
                'message': f'缺少必填字段: {field}'
            })
    
    # 测试连接
    success, message = test_connection(
        data['host'],
        data['port'],
        data['username'],
        data['password'],
        data['database']
    )
    
    # 如果提供了数据源ID，更新状态
    if 'datasource_id' in data:
        datasource = DataSource.query.get(data['datasource_id'])
        if datasource:
            datasource.status = 'connected' if success else 'disconnected'
            datasource.last_test_time = datetime.now()
            db.session.commit()
    
    if success:
        return jsonify({
            'code': 200,
            'message': '连接成功'
        })
    else:
        return jsonify({
            'code': 400,
            'message': f'连接失败: {message}'
        })

@datasource_bp.route('/<int:id>/test_connection', methods=['POST'])
def test_datasource_connection_by_id(id):
    """通过ID测试数据源连接"""
    datasource = DataSource.query.get_or_404(id)
    
    # 测试连接
    success, message = test_connection(
        datasource.host,
        datasource.port,
        datasource.username,
        datasource.password,
        datasource.database
    )
    
    # 更新状态
    datasource.status = 'connected' if success else 'disconnected'
    datasource.last_test_time = datetime.now()
    db.session.commit()
    
    if success:
        return jsonify({
            'code': 200,
            'message': '连接成功',
            'data': datasource.to_dict()
        })
    else:
        return jsonify({
            'code': 400,
            'message': f'连接失败: {message}',
            'data': datasource.to_dict()
        })

@datasource_bp.route('/<int:id>/tables', methods=['GET'])
def get_datasource_tables(id):
    """获取数据源的所有表"""
    datasource = DataSource.query.get_or_404(id)
    
    tables = get_tables(
        datasource.host,
        datasource.port,
        datasource.username,
        datasource.password,
        datasource.database
    )
    
    return jsonify({
        'code': 200,
        'data': tables
    })

@datasource_bp.route('/<int:id>/tables/<table_name>/schema', methods=['GET'])
def get_datasource_table_schema(id, table_name):
    """获取数据源表的结构"""
    datasource = DataSource.query.get_or_404(id)
    
    schema = get_table_schema(
        datasource.host,
        datasource.port,
        datasource.username,
        datasource.password,
        datasource.database,
        table_name
    )
    
    return jsonify({
        'code': 200,
        'data': schema
    })

@datasource_bp.route('/<int:id>/tables/<table_name>/fields', methods=['GET'])
def get_datasource_table_fields(id, table_name):
    """获取数据源表的字段列表"""
    datasource = DataSource.query.get_or_404(id)
    
    schema = get_table_schema(
        datasource.host,
        datasource.port,
        datasource.username,
        datasource.password,
        datasource.database,
        table_name
    )
    
    # 简化字段信息，只返回名称和类型
    fields = [{'name': field['name'], 'type': field['type']} for field in schema]
    
    return jsonify({
        'code': 200,
        'data': fields
    })

@datasource_bp.route('/refresh_status', methods=['POST'])
def refresh_all_datasource_status():
    """刷新所有数据源的连接状态"""
    datasources = DataSource.query.all()
    updated_count = 0
    
    for datasource in datasources:
        try:
            success, _ = test_connection(
                datasource.host,
                datasource.port,
                datasource.username,
                datasource.password,
                datasource.database
            )
            datasource.status = 'connected' if success else 'disconnected'
            datasource.last_test_time = datetime.now()
            updated_count += 1
        except Exception:
            datasource.status = 'disconnected'
            datasource.last_test_time = datetime.now()
    
    db.session.commit()
    
    return jsonify({
        'code': 200,
        'message': f'已更新 {updated_count} 个数据源的状态'
    })